package cz.vutbr.fit.xzemko01.tfmcbs.validation.validators;

import java.util.Map;

import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;

import cz.vutbr.fit.xzemko01.tfmcbs.model.CompositeComponent;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Provider;
import cz.vutbr.fit.xzemko01.tfmcbs.model.ProvidingPort;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Realization;
import cz.vutbr.fit.xzemko01.tfmcbs.model.SimpleComponent;
import cz.vutbr.fit.xzemko01.tfmcbs.validation.utils.DiagnosticBuilder;

public class ProviderValidator implements Validator<Provider>  {
	
	private static ProviderValidator providerValidator;
	
	private ProviderValidator() {
	}
	
	public static Validator<Provider> getInstance() {
		if(providerValidator == null) {
			providerValidator = new ProviderValidator();
		}
		
		return providerValidator;
	}

	@Override
	public boolean validate(Provider provider, DiagnosticChain diagnostics, Map<Object, Object> context) {
		boolean result = validateUniqueRealization(provider, diagnostics, context);
		return result;
	}
	
	private boolean validateUniqueRealization(Provider provider, DiagnosticChain diagnostics, Map<Object, Object> context) {
		if(provider == null || provider.getRealizations() == null) {
			return true;
		}
		
		int i = 0;
		boolean result = true;
		
		for(Realization realization1 : provider.getRealizations()) {
			i++;
			for(int j = i; j < provider.getRealizations().size(); j++) {
				Realization realization2 = provider.getRealizations().get(j);
				
				if(realization1.getInterface() != null
						&& realization2.getInterface() != null
						&& realization1.getInterface() == realization2.getInterface()) 
				{
					String errorMessage = "";
					if(provider instanceof SimpleComponent) {
						errorMessage += "Component \"" + ((SimpleComponent) provider).getName() + "\" ";
					} else if(provider instanceof ProvidingPort) {
						ProvidingPort port = (ProvidingPort) provider;
						errorMessage += "Port \"" + port.getName() + "\"";
						
						CompositeComponent component = port.getComponent();
						if(component != null) {
							errorMessage += " in the component \"" + component.getName() + "\"";
						}
					}
					
					errorMessage += "realizate interface \"" + realization1.getInterface().getName() + "\" two or more times.";
					
					Diagnostic diagnostic = 
							new DiagnosticBuilder(provider).setMessage(errorMessage).build();
					
					diagnostics.add(diagnostic);
					result = false;
				}
			}
		}
		return result;
	}
}
